package cn.com.infcn.monitor.web;

import java.io.Serializable;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

public class IFCCounterError implements Serializable{
	public static final String REQUEST_KEY = "ifcmonitor.request";
	private static final long serialVersionUID = 5690702786722045646L;
	@SuppressWarnings("all")
	private static final ThreadLocal<HttpServletRequest> HTTP_SERVLET_REQUEST_CONTEXT = new ThreadLocal<HttpServletRequest>();
	private final long time;
	private final String remoteUser;
	private final String httpRequest;
	private final String message;
	private final String stackTrace;

	IFCCounterError(String message, String stackTrace) {
		super();
		assert message != null;
		this.time = System.currentTimeMillis();
		this.message = message;
		this.stackTrace = stackTrace;
		final HttpServletRequest currentRequest = getCurrentRequest();
		if (currentRequest == null) {
			this.remoteUser = null;
			this.httpRequest = null;
		} else {
			unbindRequest();
			try {
				this.httpRequest = (String) currentRequest.getAttribute(REQUEST_KEY);
				this.remoteUser = currentRequest.getRemoteUser();
			} finally {
				bindRequest(currentRequest);
			}
		}
	}

	public static void bindRequest(HttpServletRequest request) {
		if (request != null) {
			HTTP_SERVLET_REQUEST_CONTEXT.set(request);
		}
	}

	private static HttpServletRequest getCurrentRequest() {
		return HTTP_SERVLET_REQUEST_CONTEXT.get();
	}

	public static void unbindRequest() {
		HTTP_SERVLET_REQUEST_CONTEXT.remove();
	}

	long getTime() {
		return time;
	}

	Date getDate() {
		return new Date(time);
	}

	String getRemoteUser() {
		return remoteUser;
	}

	String getHttpRequest() {
		return httpRequest;
	}

	String getMessage() {
		return message;
	}

	String getStackTrace() {
		return stackTrace;
	}

	@Override
	public String toString() {
		return getClass().getSimpleName() + "[message=" + getMessage() + ']';
	}
}
